<?php

namespace App\Http\Controllers\Api\v1;

use App\Handlers\KeysHandler;
use App\Models\Account;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
use App\Http\Requests\Api\v1\AdsRequest;
use App\Models\Ad;
use App\Models\AdsConfig;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Cache;
use App\Http\Resources\AdsConfigResource;
use Illuminate\Support\Facades\DB;

/**
 * 文章
 * @package App\Http\Controllers\Api\v1
 */
class AdsController extends Controller
{

    public function config()
    {
        $data =  Cache::remember(KeysHandler::ADS_CONFIGS, KeysHandler::ADS_CONFIGS_TTL, function ()  {
            $data = AdsConfig::query()->where('status','=', 1)->orderBy('sort')->orderBy('id')->get();
            return $data;
        });
        return $this->success(AdsConfigResource::collection($data));
    }



    public function store(AdsRequest $request, Ad $ad)
    {
        $adsconfig = AdsConfig::find($request->ads_config_id);
        if(!$adsconfig){
            $this->errorResponse(Response::HTTP_OK, trans('error.500002'), 500002);
        }
        $goods_id = $request->goods_id;
        try {
            $user = User::getUser(['tiktokid'=>$request->header('Userid')]);
            $res =  DB::transaction(function () use ($user, $adsconfig,$goods_id) {
                $user = User::query()->where('id', '=', $user->id)->lockForUpdate()->first();
                if ($adsconfig->amount > $user->balance) {
                    return 10016;
                }
                //扣余额，写流水，创建表
                $ad = Ad::query()->create([
                    'user_id' => $user->id,
                    'goods_id' => $goods_id,
                    'ads_config_id' => $adsconfig->id,
                    'amount' => $adsconfig->amount,
                    'click' => $adsconfig->click
                ]);
                $user->decrement('balance', $adsconfig->amount);
                $account_amount = bcmul($adsconfig->amount, -1);
                (new Account())->store($user->id, $account_amount, Account::AD_COST, 0, $ad->id);
                return 1;
            });

            if ($res == 1) {
                return $this->success();
            }
            return $this->fail($res, trans('error.' . $res));
        } catch (Exception $exception) {
            return $this->fail(40050, trans('error.40050'));
        }
    }


}
